<?php
namespace app\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Config;

class Index extends Base
{
    protected $_special_category_names = [
        'featured' => '推薦', 
        'category' => '', 
        'popular' => '熱門'
    ];
    /**
     * 初始化方法
     */
    public function _initialize()
    {
        parent::_initialize();
        
        
    }
    

    
    /**
     * 首页
     */
    public function index()
    {
        $siteConfig = Config::get('app');
        // 获取推荐的壁纸 - 电脑桌布
        $featuredDesktopWallpapers = Db::name('wallpaper')
            ->where('featured', 1)
            ->where('noindex', 0)
            ->where('status', 1)
            ->where('type', 'desktop')
            ->order('update_time desc')
            ->limit($siteConfig['featured_desktop_limit'])
            ->select();
            
        $featuredDesktopWallpapers = $this->_formatWallpaper($featuredDesktopWallpapers);
        // 获取推荐的壁纸 - 手机桌布
        $featuredMobileWallpapers = Db::name('wallpaper')
            ->where('featured', 1)
            ->where('status', 1)
            ->where('noindex', 0)
            ->where('type', 'mobile')
            ->order('update_time desc')
            ->limit($siteConfig['featured_mobile_limit'])
            ->select();
            
        $featuredMobileWallpapers = $this->_formatWallpaper($featuredMobileWallpapers);
        // debug_dump($featuredMobileWallpapers);
        // 获取最新壁纸 (所有类型)
        $latestDesktopWallpapers = Db::name('wallpaper')
            ->where('status', 1)
            ->where('noindex', 0)
            ->where('type', 'desktop')
            ->order('update_time desc')
            ->limit($siteConfig['latest_desktop_limit'])
            ->select();
            
        $latestDesktopWallpapers = $this->_formatWallpaper($latestDesktopWallpapers);
        
        $latestMobileWallpapers = Db::name('wallpaper')
            ->where('status', 1)
            ->where('noindex', 0)
            ->where('type', 'mobile')
            ->order('update_time desc')
            ->limit($siteConfig['latest_mobile_limit'])
            ->select();

        $latestMobileWallpapers = $this->_formatWallpaper($latestMobileWallpapers);

        // 获取热门壁纸 - 电脑桌布
        $popularDesktopWallpapers = Db::name('wallpaper')
            ->where('status', 1)
            ->where('noindex', 0)
            ->where('type', 'desktop')
            ->order('download_cnt desc, view_cnt desc')
            ->limit($siteConfig['popular_desktop_limit'])
            ->select();
            
        $popularDesktopWallpapers = $this->_formatWallpaper($popularDesktopWallpapers);
        
        // 获取热门壁纸 - 手机桌布
        $popularMobileWallpapers = Db::name('wallpaper')
            ->where('status', 1)
            ->where('noindex', 0)
            ->where('type', 'mobile')
            ->order('download_cnt desc, view_cnt desc')
            ->limit($siteConfig['popular_mobile_limit'])
            ->select();
            
        $popularMobileWallpapers = $this->_formatWallpaper($popularMobileWallpapers);

        $loading_time = config('app.generate_loading_time');

        $links_list = Db::name('links')->select();

        $this->assign('links_list', $links_list);
        $this->assign('loading_time', json_encode($loading_time));
        $this->assign('latestDesktopWallpapers', $latestDesktopWallpapers);
        $this->assign('latestMobileWallpapers', $latestMobileWallpapers);
        $this->assign('featuredDesktopWallpapers', $featuredDesktopWallpapers);
        $this->assign('featuredMobileWallpapers', $featuredMobileWallpapers);
        $this->assign('popularDesktopWallpapers', $popularDesktopWallpapers);
        $this->assign('popularMobileWallpapers', $popularMobileWallpapers);

        $limit_service = new \app\service\UsageLimitService();
        $daily_limit = $limit_service->getDailyLimits();
        $used_limit = $limit_service->getUsedCount();

        $this->assign('daily_limit', $daily_limit);
        $this->assign('used_limit', $used_limit);

        $this->assign([
            'page_title' => '電腦桌布 手機桌布',
            'page_description' => '壁響網提供超過10000張免費高清4K桌布下載，包括風景、動漫、遊戲、美女等分類的電腦桌布和手機桌布。每日更新，支持多種分辨率，讓您的設備屏幕更加精彩。',
        ]);
        return $this->fetch();
    }
    
 
    public function specialCategory($name, $type){
        if (!in_array($name, ['featured', 'category', 'popular']) || empty($type)) {
            header('HTTP/1.1 404 Not Found');
            $this->error('分類不存在');
        }
        if (!isset($this->_category_types[$type])){
            header('HTTP/1.1 404 Not Found');
            throw new \think\exception\HttpException(404, '404');
        }

        $canonical = 'https://'.$this->_site_domain.'/'.rawurlencode($name).'/'.rawurlencode($type).'/';
        $route = Request::instance()->route();
        if (!isset($route['name']) || empty($route['name'])) {
            $canonical = 'https://'.$this->_site_domain.'/category/'.rawurlencode($type).'/';
        }

        $name_label = $this->_special_category_names[$name];
        $orderBy = 'create_time desc';
        $where['status'] = 1;

        if ($name == 'featured') {
            $where['featured'] = 1;
            $where['noindex'] = 0;
        } else if ($name == 'popular') {
            $where['noindex'] = 0;
            $where['download_cnt'] = ['gt', 2];
            $orderBy = 'download_cnt desc, view_cnt desc';
        } else if ($name == 'category') {
            $orderBy = 'create_time desc';
        }
        $is_dynamic = false;
        // 判断是否指定了类型
        $sel_type_label = '';
        if ($type && in_array($type, ['電腦桌布', '手機桌布', '動態電腦桌布', '動態手機桌布'])) {
            $where['type'] = $this->_category_types[$type];
            $sel_type_label = $type;
            $is_dynamic = strpos($type, '動態') !== false;
        }

        $siteConfig = Config::get('app');
        $pageSize = $siteConfig['page_size'];

        // 获取壁纸列表
        $wallpapers_obj = Db::name('wallpaper')
            ->where($where)
            ->order($orderBy)
            ->paginate( $pageSize);
                
        $page = $wallpapers_obj->render();
        $wallpapers = $wallpapers_obj->toArray()['data'];
        $wallpapers = $this->_formatWallpaper($wallpapers);
        $total = $wallpapers_obj->total();

        $cache_top_category_key = 'last_update_time_top_category_'.$this->_category_types[$type];
        $last_update_time = cache($cache_top_category_key);
        
        
        
        $this->assign('wallpapers', $wallpapers);
        $this->assign('type', $type);
        $this->assign('name', $name);
        $this->assign('sel_type_label', $sel_type_label);
        $this->assign('name_label', $name_label);
        $this->assign('canonical', $canonical);
        $this->assign('is_dynamic', $is_dynamic);
        $this->assign('total',$total);
        $this->assign('page',$page);
        $this->assign('last_update_time',$last_update_time);

        $this->assign([
            'page_title' =>  $name_label . $sel_type_label,
            'page_description' => '壁響網' . $name_label . $sel_type_label . '專區，精選優質高清桌布免費下載。涵蓋風景、動漫、遊戲、美女等熱門分類，支持電腦和手機多種分辨率，每日更新最新桌布資源。',
        ]);
        return $this->fetch();
    }
    /**
     * 分类页
     */
    public function category($type,$name)
    {
        // 检查分类是否存在
        $category = $this->_category_names[$name];
        if (!$category || empty($type)) {
            $this->error('分類不存在');
        }
        $sel_type_label = '';
        $is_dynamic = false;
        if ($type && in_array($type, ['電腦桌布', '手機桌布', '動態電腦桌布', '動態手機桌布'])) {
            $where['type'] = $this->_category_types[$type];
            $sel_type_label = $type;
            $is_dynamic = strpos($type, '動態') !== false;
        }
        // debug_dump($where);
        
        $siteConfig = Config::get('app');
        $pageSize = $siteConfig['page_size'];
        $where['status'] = 1;
        $where['category_id'] = $category['id'];
        
        $orderBy = 'create_time desc';
        $wallpapers_obj = Db::name('wallpaper')
            ->where($where)
            ->order($orderBy)
            ->paginate( $pageSize);
            
        $page = $wallpapers_obj->render();
        $wallpapers = $wallpapers_obj->toArray()['data'];
        $wallpapers = $this->_formatWallpaper($wallpapers);
        $total = $wallpapers_obj->total();

        $cache_category_key = 'last_update_time_category_id_'.$category['id'] .'_'.$this->_category_types[$type];
        $last_update_time = cache($cache_category_key);

        
       
        // debug_dump($category);
        $this->assign('category_info', $category);
        $this->assign('wallpapers', $wallpapers);
        $this->assign('type', $type);
        $this->assign('sel_type_label', $sel_type_label);
        $this->assign('is_dynamic', $is_dynamic);
        $this->assign('total',$total);
        $this->assign('page',$page);
        $this->assign('last_update_time',$last_update_time);

        $this->assign([
            'page_title' => $category['name'].$sel_type_label,
            'page_description' => '免費下載' . $category['name'] . $sel_type_label . '，壁響網提供' . $category['name'] . '主題的高清4K' . $sel_type_label . '。精美' . $category['name'] . '圖片，多種分辨率可選，讓您的設備屏幕展現' . $category['name'] . '之美。',
        ]);
        return $this->fetch();
    }
    
    /**
     * 详情页
     */
    public function detail($type,$name,$title)
    {
        $title = trim($title);
        $type_where = $this->_category_types[$type];
        // 检查壁纸是否存在
        $wallpapers = Db::name('wallpaper')->where('title', $title)->where('type', $type_where)->where('status', 1)->order('id desc')->select();
        if (!$wallpapers) {
            header('HTTP/1.1 404 Not Found');
            throw new \think\exception\HttpException(404, '404');
        }
        $wallpapers = $this->_formatWallpaper($wallpapers);
        $wallpaper_first = $wallpapers[count($wallpapers) - 1];
        $wallpapers_type = $wallpaper_first['type'];
        $wallpapers_type_name = $this->_type_names[$wallpapers_type];
        $wallpapers_category_id = $wallpaper_first['category_id'];
        $wallpapers_category_name = $this->_category_names[$wallpaper_first['category_name']]['name'];

        $wallpapers_title = $wallpaper_first['title'];
        $wallpapers_noindex = $wallpaper_first['noindex'];

        

        if ($type != $wallpapers_type_name || $name != $wallpapers_category_name) {
            header('HTTP/1.1 404 Not Found');
            throw new \think\exception\HttpException(404, '404');
        }
        
                
        // 将标签字符串转换为数组
        $tags = $wallpaper_first['tags'];
        
        
        // 获取相关推荐（同分类和同类型的其他壁纸）
        $relatedWallpapers = [];
        
        // 检查用户收藏状态
        $isFavorited = false;
        
        $this->assign('wallpaper_first', $wallpaper_first);
        $this->assign('wallpapers', $wallpapers);

        $this->assign('tags', $tags);
        $this->assign('relatedWallpapers', $relatedWallpapers);
        $this->assign('isFavorited', $isFavorited);
        $this->assign('wallpapers_type', $wallpapers_type);
        $this->assign('wallpapers_type_name', $wallpapers_type_name);
        $this->assign('wallpapers_category_name', $wallpapers_category_name);
        $this->assign('wallpapers_title', $wallpapers_title);
        $this->assign('wallpapers_noindex', $wallpapers_noindex);

        $type_label = $wallpapers_type == 'mobile' ? '手機桌布' : '電腦桌布';
        $page_title  = $wallpapers_title;
        if (mb_strlen($page_title) > 40){
            $page_title = mb_substr($page_title, 0, 60) . '...';
        }
        $page_title = $page_title . $type_label . ' 免費下載';;

        $device_type = $wallpapers_type == 'mobile' || $wallpapers_type == 'dynamic_mobile' ? '手機' : '電腦';
        $this->assign([
            'page_title' => $page_title,
            'page_description' => '免費下載《' . $wallpapers_title . '》高清' . $type_label . '，壁響網提供高清4K分辨率版本，精美' . $wallpapers_category_name . '主題桌布，適用'. $device_type .'鎖屏或' . $device_type . '桌面背景，一鍵下載，讓您的' . $device_type . '屏幕更加個性化。',
        ]);
        return $this->fetch();
    }
    
    
    /**
     * 搜索壁纸
     */
    public function search()
    {
        $keyword = input('keyword/s', '');
        if (empty($keyword)) {
            $this->error('請輸入搜索關鍵詞');
        }
        
        $siteConfig = Config::get('app');
        
        // 获取分页参数
        $pageSize = $siteConfig['page_size'];
        
        // 获取类型参数
        $type = input('type', '');
        $where = ['status' => 1];
        if ($type && in_array($type, ['desktop', 'mobile'])) {
            $where['type'] = $type;
        }
        
        // 搜索壁纸（标题、描述、标签中包含关键字的）
        $wallpapers_obj = Db::name('wallpaper')
            ->where($where)
            ->where(function($query) use ($keyword) {
                $query->whereOr('title', 'like', "%{$keyword}%")
                    ->whereOr('description', 'like', "%{$keyword}%")
                    ->whereOr('tag_name', 'like', "%{$keyword}%");
            })
            ->order('id desc')
            ->paginate( $pageSize);
            
        $page = $wallpapers_obj->render();
        $total = $wallpapers_obj->total();
        $wallpapers = $wallpapers_obj->toArray()['data'];
            
        $wallpapers = $this->_formatWallpaper($wallpapers);
        
        // 构建分页
        
        $this->assign('keyword', $keyword);
        $this->assign('wallpapers', $wallpapers);
        $this->assign('currentPage', $page);
        $this->assign('total',$total);
        $this->assign('page',$page);
        $this->assign('type', $type);

        $this->assign([
            'page_title' => '搜索'.$keyword,
            'page_description' => '搜索"' . $keyword . '"相關桌布，壁響網為您找到' . $total . '張高清桌布。包括' . $keyword . '主題的電腦桌布和手機桌布，多種分辨率免費下載，滿足您的個性化需求。',
        ]);
        return $this->fetch();
    }
    public function generate()
    {
        $wall_type = input('wall_type', 'mobile', 'trim');
        if (!in_array($wall_type, ['mobile', 'desktop'])) {
            return json(['code' => 0, 'msg' => '請輸入正確的桌布類型']);
        }
        $promptText = input('prompt_text', '', 'trim');
        if (empty($promptText)) {
            return json(['code' => 0, 'msg' => '請輸入提示文字']);
        }
        $quality = input('quality', 'default', 'trim');
        if (!in_array($quality, ['default', 'hd', '4k'])) {
            return json(['code' => 0, 'msg' => '請輸入正確的質量']);
        }
        // 检查每日限制
        $limit_service = new \app\service\UsageLimitService();
        $limitCheck = $limit_service->checkDailyLimit();
        if (!$limitCheck['status']) {
            if ($limitCheck['user_type'] == 'guest'){
                return json(['code' => 411, 'msg' => $limitCheck['message']]);
            }else{
                return json(['code' => 412, 'msg' => $limitCheck['message']]);
            }
        }
        try{
            $service = new \app\service\ImageGenerateService();
            $result = $service->generateImage($promptText, $wall_type, $quality);
            $generated_image = $result['generated_image'];
            $ai_processing_time = $result['ai_processing_time'];
            // $prompt = $result['prompt'];

            $user_service = new \app\service\UserService();
            $user_id = $user_service->getUserId();
            $id = db('wallpaper_generate')->insertGetId([
                'user_id' => $user_id,
                'prompt_text' => $promptText,
                'wall_type' => $wall_type,
                'quality' => $quality,
                'generated_image' => $generated_image,
                'ai_processing_time' => $ai_processing_time,
                // 'prompt' => $prompt,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            if (!$id){
                return json(['code' => 0, 'msg' => '生成失敗']);
            }
            $limit_service->recordOperation('completed');
        }catch(\Exception $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => '生成成功', 'data' => $result]);        
    }

    /**
     * 增加壁纸浏览量
     * @param int $id 壁纸ID
     */
    public function increment_view_cnt($id){
        
        Db::name('wallpaper')->where('id', $id)->setInc('view_cnt');
    }
    /**
     * 关于我们
     */
    public function about()
    {
        $this->assign([
            'page_title' => '關於我們',
            'page_description' => '壁響網是專業的桌布分享平台，致力於提供高品質免費桌布下載服務。了解我們的發展歷程、企業理念和專業團隊，為用戶打造最佳的桌布體驗。',
        ]);
        return $this->fetch();
    }

    /**
     * 联系我们
     */
    public function contact()
    {
        $this->assign([
            'page_title' => '聯繫我們',
            'page_description' => '聯繫壁響網客服團隊，我們提供7x24小時在線支持。如有桌布下載問題、版權咨詢或合作建議，歡迎通過多種方式與我們取得聯繫。',
        ]);
        return $this->fetch();
    }

    /**
     * 使用条款
     */
    public function terms()
    {
        $this->assign([
            'page_title' => '使用條款',
            'page_description' => '壁響網使用條款和服務協議，詳細說明用戶權利義務、桌布使用規範、版權保護政策等重要條款。使用本站服務前請仔細閱讀並同意相關條款。',
        ]);
        return $this->fetch();
    }

    /**
     * 隐私政策
     */
    public function privacy()
    {
        $this->assign([
            'page_title' => '隱私政策',
            'page_description' => '壁響網隱私保護政策，詳細說明個人信息收集、使用、存儲和保護措施。我們承諾保護用戶隱私安全，遵循相關法律法規，確保信息安全。',
        ]);
        return $this->fetch();
    }

    
    
}
